package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.common.constant.ProductContant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.entity.vo.AttrRespVo;
import com.atguigu.gulimall.product.entity.vo.AttrVo;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    final
    AttrAttrgroupRelationService relationService;
    final
    AttrGroupService attrGroupService;
    final
    CategoryService categoryService;

    public AttrServiceImpl(AttrAttrgroupRelationService relationService, AttrGroupService attrGroupService, CategoryService categoryService) {
        this.relationService = relationService;
        this.attrGroupService = attrGroupService;
        this.categoryService = categoryService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attrVo) throws RuntimeException {
        AttrEntity entity = new AttrEntity();
        BeanUtil.copyProperties(attrVo, entity);
        this.save(entity);
        if (attrVo.getAttrType() == ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //保存关联关系
            AttrAttrgroupRelationEntity attrgroupRelation = new AttrAttrgroupRelationEntity();
            attrgroupRelation.setAttrId(entity.getAttrId());
            attrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            relationService.save(attrgroupRelation);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ?
                ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode()
                : ProductContant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //attr_id  attr_name
        String key = (String) params.get("key");
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        if (StrUtil.isNotEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrRespVo> collect = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo respVo = new AttrRespVo();
            BeanUtil.copyProperties(attrEntity, respVo);
            AttrAttrgroupRelationEntity attrgroupRelation = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (attrgroupRelation != null) {
                AttrGroupEntity attrGroup = attrGroupService.getById(attrgroupRelation.getAttrGroupId());
                if (attrGroup != null) {
                    respVo.setGroupName(StrUtil.isNotEmpty(attrGroup.getAttrGroupName()) ? attrGroup.getAttrGroupName() : "暂无分组");
                } else {
                    respVo.setGroupName("暂无分组");
                }
            }
            CategoryEntity category = categoryService.getById(attrEntity.getCatelogId());
            if (category != null) {
                respVo.setCatelogName((StrUtil.isNotEmpty(category.getName())) ? category.getName() : "暂无分类");
            }
            return respVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Cacheable(value = "attr", key = "'attrInfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtil.copyProperties(attrEntity, respVo);
        if (attrEntity.getAttrType() == ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //1.设置分组信息
            AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroup = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (attrGroup != null) {
                    respVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
        }
        //2.设置分类信息
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        respVo.setCatelogPath(catelogPath);
        CategoryEntity category = categoryService.getById(attrEntity.getCatelogId());
        if (category != null) {
            respVo.setCatelogName(category.getName());
        }
        return respVo;
    }

    @Override
    public void updateAttr(AttrVo attrVo) throws RuntimeException {
        AttrEntity attr = new AttrEntity();
        BeanUtil.copyProperties(attrVo, attr);
        this.updateById(attr);
        if (attrVo.getAttrType() == ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //更新关联关系
            AttrAttrgroupRelationEntity attrgroupRelation = new AttrAttrgroupRelationEntity();
            attrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            attrgroupRelation.setAttrId(attrVo.getAttrId());
            long count = relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if (count > 0) {
                relationService.update(attrgroupRelation, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            } else {
                relationService.save(attrgroupRelation);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds.size() == 0 || attrIds == null) {
            return null;
        }
        List<AttrEntity> attrList = this.listByIds(attrIds);
        return attrList;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) throws RuntimeException {
        relationService.deleteBatchRelation(vos);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）当前分类下的其他属性
        List<AttrGroupEntity> group = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        if (collect == null || collect.size() == 0) {
            return null;
        }
        //2.2）这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3）从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductContant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        PageUtils pageUtils = getPageUtils(params, wrapper, key);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }

    /**
     * 获取分页数据
     *
     * @param params
     * @param wrapper
     * @param key
     * @return
     */
    private PageUtils getPageUtils(Map<String, Object> params, QueryWrapper<AttrEntity> wrapper, String key) {
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(iPage);
        return pageUtils;
    }

}